<template>
  <div class="information">
    <div>
      <div class="title">
        <h1 style="color: #337ECC;font-size: 40px">企业信息</h1>
        <div>
          <CopyOutlined class="icon"/>
          <TagOutlined class="icon"/>
        </div>


      </div>
    </div>
    <div style="border: 2px solid #337ECC; padding: 20px;border-top: 30px solid #337ECC; border-radius: 10px">

      <a-form
          ref="formRef"
          :label-col="labelCol"
          :model="formState"
          :rules="rules"
          :wrapper-col="wrapperCol"
      >
        <a-divider orientation="left" style="color:#337ECC; font-size: 20px">基本信息</a-divider>
        <div class="basic">


          <div class="basicInfo">
            <a-form-item ref="enterprise_name" label="企业名称" name="enterprise_name" style="width: 300px">
              <a-input v-model:value="formState.enterprise_name" :bordered="isBordered" :disabled="!isBordered"/>
            </a-form-item>

            <a-form-item ref="enterprise_certification_status" label="审核状态"
                         name="enterprise_certification_status" style="width: 300px">
              <a-input v-model:value="formState.enterprise_certification_status" :bordered="isBordered"
                       :disabled="true"/>
            </a-form-item>
            <div v-show="formState.enterprise_certification_status==='审核不通过'">
              <a-form-item ref="enterprise_certification_refuse" label="拒绝原因"
                           name="enterprise_certification_refuse">
                <a-textarea v-model:value="formState.enterprise_certification_refuse"
                            :auto-size="{minRows: 3, maxRows: 20}"
                            show-count
                            style="width: 500px"
                />
              </a-form-item>
            </div>

            <a-form-item ref="enterprise_industry" label="所属行业" name="enterprise_industry"
                         style="width: 300px">
              <a-input v-model:value="formState.enterprise_industry" :bordered="isBordered" :disabled="!isBordered"/>
            </a-form-item>
            <a-form-item ref="enterprise_size" label="企业规模" name="enterprise_size" style="width: 300px">
              <a-input v-model:value="formState.enterprise_size" :bordered="isBordered" :disabled="!isBordered"/>
            </a-form-item>
            <a-form-item ref="enterprise_foundation_date" label="成立时间" name="enterprise_foundation_date"
                         style="width: 300px">
              <a-date-picker
                  v-model:value="formState.enterprise_foundation_date"
                  :bordered="isBordered" :disabled="!isBordered"
              />
            </a-form-item>
            <a-form-item ref="enterprise_type" label="企业性质" name="enterprise_type" style="width: 300px">
              <a-select v-model:value="formState.enterprise_type" :bordered="isBordered" :disabled="!isBordered"
                        placeholder="选择状态">
                <a-select-option value="私企">私企</a-select-option>
                <a-select-option value="国企">国企</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item ref="enterprise_website" label="企业官网" name="enterprise_website"
                         style="width: 300px">
              <a-input v-model:value="formState.enterprise_website" :bordered="isBordered" :disabled="!isBordered"/>
            </a-form-item>
            <a-form-item ref="enterprise_social_media_links" label="社交媒体" name="enterprise_social_media_links"
                         style="width: 300px">
              <a-input v-model:value="formState.enterprise_social_media_links" :bordered="isBordered"
                       :disabled="!isBordered"/>
            </a-form-item>

          </div>

          <div class="update">
            <a-upload
                v-model:file-list="fileList"
                :before-upload="beforeUpload"
                :disabled="!isBordered"
                :show-upload-list="false"
                action="http://localhost:8080/file/upload"
                class="avatar-uploader"
                list-type="picture-card"
                name="file"
                style="width: 100%; height: 100%;"
                @change="handleChange"
            >
              <img v-if="imageUrl" :src="imageUrl" alt="avatar" style="width: 100%; height: 100%; border-radius: 50%"/>
              <div v-else>
                <loading-outlined v-if="loading"></loading-outlined>
                <plus-outlined v-else></plus-outlined>
                <div class="ant-upload-text">上传LOGO</div>
              </div>
            </a-upload>
          </div>
        </div>
        <div class="school">


          <a-form-item ref="enterprise_email" label="企业邮箱" name="enterprise_email"
                       style="width: 300px">
            <a-input v-model:value="formState.enterprise_email" :bordered="isBordered" :disabled="!isBordered"/>
          </a-form-item>
          <a-form-item ref="enterprise_address" label="企业地址" name="enterprise_address"
                       style="width: 500px">
            <a-input v-model:value="formState.enterprise_address" :bordered="isBordered" :disabled="!isBordered"/>
          </a-form-item>
          <a-form-item ref="enterprise_profile" label="企业简介" name="enterprise_profile">
            <a-textarea v-model:value="formState.enterprise_profile"
                        :auto-size="{minRows: 3, maxRows: 20}"
                        :bordered="isBordered"
                        :disabled="!isBordered"
                        :maxlength="500"
                        show-count
                        style="width: 800px"
            />
          </a-form-item>
          <a-form-item ref="enterprise_name" label="上传资质" name="enterprise_name" style="width: 800px">
            <a-upload
                v-model:file-list="certificateList"
                name="file"
                action="http://localhost:8080/file/upload"
                :headers="headers"
                @change="handleChangeVerification"
                @remove="handleRemove"

            >
              <a-button :disabled="!isBordered">
                <upload-outlined></upload-outlined>
                请上传营业执照，法人信息等相关资质文件
              </a-button>
            </a-upload>
          </a-form-item>
        </div>
        <a-col :span="24">
          <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
            <div>
              <div v-if="isSave">
                <a-popconfirm cancel-text="取消" ok-text="确定" title="你确定保存11吗？" @confirm="save">
                  <a-button style="width:200px" type="primary">保存</a-button>
                </a-popconfirm>
                <a-popconfirm cancel-text="取消" ok-text="确定" title="你确定重置吗？" @confirm="resetForm">
                  <a-button style="margin-left: 60px; width:200px">重置</a-button>
                </a-popconfirm>
              </div>
              <div v-else>

                <div v-if="isUpdate" style="display:flex;">
                  <a-popconfirm cancel-text="取消" ok-text="确定" title="你确定保存22吗？" @confirm="update">
                    <a-button style="width:200px" type="primary">保存</a-button>
                  </a-popconfirm>

                  <a-button style="margin-left: 60px; width:200px" @click="cancel">取消</a-button>


                  <a-popconfirm cancel-text="取消" ok-text="确定" title="你确定重置吗？" @confirm="resetForm">
                    <a-button style="margin-left: 60px; width:200px">重置</a-button>
                  </a-popconfirm>
                </div>
                <div v-else>
                  <a-popconfirm cancel-text="取消" ok-text="确定" title="你确定修改吗？" @confirm="isupdate">
                    <a-button style="width:200px" type="primary">修改</a-button>
                  </a-popconfirm>


                  <a-button style="margin-left: 60px; width:200px" @click="goBack">返回</a-button>

                </div>
              </div>
            </div>

          </a-form-item>
        </a-col>
      </a-form>
    </div>
  </div>
</template>
<script setup>
import {CopyOutlined, SmileOutlined, TagOutlined} from "@ant-design/icons-vue";
import {h, onMounted, reactive, ref, toRaw} from 'vue';
import {useUserStore} from "@/stores/user.js";
import {addInformationAPI, queryInformationByUserIdAPI, updateInformationByIdAPI} from "@/apis/enterprise.js";
import {message, notification} from "ant-design-vue";
import moment from "moment";
import {useRouter} from "vue-router";
import dayjs from "dayjs";

const formRef = ref();
const formState = reactive({
  enterpriseCertificate:'',
  enterpriseCertificateFile:'',
  enterprise_name: '',
  enterprise_logo_url: '',
  enterprise_certification_status: '',
  enterprise_certification_refuse: '',
  enterprise_profile: '',
  enterprise_industry: '',
  enterprise_size: '',
  enterprise_foundation_date: '',
  enterprise_type: '',
  enterprise_address: '',
  enterprise_email: '',
  enterprise_website: '',
  enterprise_social_media_links: '',
  enterpriseUserId: '',
  account: '',
  userRole: '',
  enterpriseId: '',
});
const rules = {
  enterprise_certification_status: [
    {
      required: true,
      trigger: 'change',
    },
  ],
  enterprise_certification_refuse: [
    {
      required: true,
    },
  ],
  enterprise_name: [
    {
      required: true,
      message: '请输入企业名称！',
      trigger: 'change',
    },
  ],
  enterprise_logo_url: [
    {
      required: true,
      message: '请上传企业logo！',
      trigger: 'change',
    },
  ],
  enterprise_profile: [
    {
      required: true,
      message: '请输入企业简介！',
      trigger: 'change',
    },
  ],
  enterprise_industry: [
    {
      required: true,
      message: '请输入企业所属行业！',
      trigger: 'change',
    },
  ],
  enterprise_size: [
    {
      required: true,
      message: '请输入企业规模！',
      trigger: 'change',
    }
  ],
  enterprise_foundation_date: [
    {
      required: true,
      message: '请选择企业成立时间！',
      trigger: 'change',
    }
  ],
  enterprise_type: [
    {
      required: true,
      message: '请选择企业性质！',
      trigger: 'change',
    }
  ],
  enterprise_address: [
    {
      required: true,
      message: '请输入企业地址！',
      trigger: 'change',
    }
  ],

  enterprise_email: [
    {
      required: true,
      message: '请输入企业邮箱！',
      trigger: 'change',
    }
  ],
  enterprise_website: [
    {
      required: true,
      message: '请输入企业官网！',
      trigger: 'change',
    }
  ],
  enterprise_social_media_links: [
    {
      required: true,
      message: '请输入企业社交媒体连接！',
      trigger: 'change',
    }
  ],
};
const useStore = useUserStore();
const success = (msg) => {
  message.success(msg);
};
const save = () => {
  console.log("新增"+JSON.stringify(formState));
  formRef.value
      .validate()
      .then(async () => {
        console.log('values', formState, toRaw(formState));
        formState.account = useStore.userInfo.account;
        formState.userRole = useStore.userInfo.userRole;
        formState.enterprise_certification_status = '审核中';
        formState.enterpriseCertificate='未认证';
        formState.enterpriseCertificateFile=list.value.map((file)=>{
          return file;
        }).join(',');
        const res = await addInformationAPI(formState);
        console.log(res);
        if (res.data.flag) {
          success(res.data.message);
          // 设置一个定时器，在1秒后刷新页面
          setTimeout(() => {
            window.location.reload();
          }, 1000); // 1000毫秒 = 1秒
        } else {
          console.log('error submit!', toRaw(formState));
        }
      })
      .catch(error => {
        console.log('error', error);
      });
};
const isupdate = () => {//修改按钮
  if(formState.enterprise_certification_status === '审核中'){
    openNotification("企业信息正在审核中,不可修改，请耐心等待！", "red", 'top');
  }else {
    isUpdate.value = true;
    isBordered.value = true;
    openNotification("点击照片或输入框均可修改！", "green", 'top');
  }
}
const update = () => {
  console.log("修改"+JSON.stringify(certificateList.value));

  formRef.value
      .validate()
      .then(async () => {
        formState.enterprise_certification_status = '审核中';
        formState.enterprise_certification_refuse = '';
        formState.enterpriseCertificate='未认证';
        formState.enterpriseCertificateFile=list.value.map((file)=>{
          return file;
        }).join(',');
        const res = await updateInformationByIdAPI(formState);
        if (res.data.flag) {
          success("修改成功，请等待审核！");
          openNotification("已提交审核！", "#52C41A");
          // 设置一个定时器，在1秒后刷新页面
          setTimeout(() => {
            window.location.reload();
          }, 2000); // 1000毫秒 = 1秒
        } else {
          console.log('error submit!', toRaw(formState));
        }
      })
      .catch(error => {
        console.log('error', error);
      });
};
//重置后是否刷新
const isRefresh = ref(false);
const resetForm = () => {
  formRef.value.resetFields();
  isRefresh.value = true;
};


//控制按钮
const isSave = ref();
const isUpdate = ref(false);//是否修改
const isBordered = ref(false);//是否边框
//获取数据
//获取当前登录用户信息

const enterpriseUserId = ref(useStore.userInfo.userId);
const getData = async (enterpriseUserId) => {
  const res = await queryInformationByUserIdAPI(enterpriseUserId.value)
  if (res.data.data == null) {
    isSave.value = true;
  } else {
    isSave.value = false;
  }

  formState.enterpriseId = res.data.data.enterpriseId;
  formState.enterprise_name = res.data.data.enterpriseName;
  formState.enterpriseCertificate=res.data.data.enterpriseCertificate;
  formState.enterpriseCertificateFile=res.data.data.enterpriseCertificateFile;
  if(res.data.data.enterpriseCertificateFile!=null&&res.data.data.enterpriseCertificateFile!==''){
    certificateList.value=res.data.data.enterpriseCertificateFile.split(',').map((file)=>{
      return {
        name: file,
        url: file,
      };
    })
    len=certificateList.value.length;
    list.value=res.data.data.enterpriseCertificateFile.split(',');
    console.log('len开始长度：'+JSON.stringify(certificateList.value.length))
  }else {
    certificateList.value=[];
    len=0;
  }


  formState.enterprise_certification_status = res.data.data.enterpriseCertificationStatus;
  formState.enterprise_certification_refuse = res.data.data.enterpriseCertificationRefuse;
  formState.enterprise_profile = res.data.data.enterpriseProfile;
  formState.enterprise_industry = res.data.data.enterpriseIndustry;
  formState.enterprise_size = res.data.data.enterpriseSize;
  formState.enterprise_foundation_date = dayjs(res.data.data.enterpriseFoundationDate, 'YYYY-MM-DD');
  formState.enterprise_type = res.data.data.enterpriseType;
  formState.enterprise_address = res.data.data.enterpriseAddress;
  formState.enterprise_email = res.data.data.enterpriseEmail;
  formState.enterprise_website = res.data.data.enterpriseWebsite;
  formState.enterprise_social_media_links = res.data.data.enterpriseSocialMediaLinks;
  formState.enterprise_logo_url = res.data.data.enterpriseLogoUrl;
  formState.enterpriseUserId = enterpriseUserId.value;

  //获取图片
  imageUrl.value = "http://localhost:8080/file/download?name=" + res.data.data.enterpriseLogoUrl;
  console.log(imageUrl.value)

}


//生命周期
onMounted(() => {
  getData(enterpriseUserId);
});

//上传照片
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

const fileList = ref([]);
const loading = ref(false);
const imageUrl = ref('');
const handleChange = info => {
  if (info.file.status === 'uploading') {
    loading.value = true;
    return;
  }
  if (info.file.status === 'done') {
    // Get this url from response in real world.
    getBase64(info.file.originFileObj, base64Url => {
      imageUrl.value = base64Url;
      loading.value = false;
    });
    formState.enterprise_logo_url = fileList.value[0].response.data;
    console.log(formState.enterprise_logo_url)

  }
  if (info.file.status === 'error') {
    loading.value = false;
    message.error('upload error');
  }
};
const beforeUpload = file => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};

//提示框
const openNotification = (des, col, placement) => {
  notification.open({
    message: '温馨提示！！！',
    description: des, placement,
    icon: () =>
        h(SmileOutlined, {
          style: {color: col},
        }),
  });
};

const router = useRouter();
const goBack = () => {
  router.go(-1); // -1 表示返回上一个页面
}
const cancel = () => {
  isSave.value = false;
  isUpdate.value = false;
  isBordered.value = false;
  if (isRefresh.value) {
    // 设置一个定时器，1秒（1000毫秒）后执行页面刷新
    setTimeout(function () {
      location.reload(); // 刷新当前页面
    }, 500);
  }
}

//上传资质
const list=ref([]);//资质列表
const certificateList = ref([]);
const headers = {
  authorization: 'authorization-text',
};
let len//认证的列表从长度，用于判断是新增还是删除
const handleChangeVerification = info => {
  if (info.file.status !== 'uploading') {
    console.log('文件长度：'+certificateList.value.length+"   len长度："+len)
    if(certificateList.value.length>len){
      len=len+1;
      console.log("上传文件"+JSON.stringify(info.file.response.data));
      list.value.push(info.file.response.data);
    }

  }
  if (info.file.status === 'done') {
    message.success(`${info.file.name} file uploaded successfully`);
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} file upload failed.`);
  }
};

function handleRemove(e) {
  console.log('删除了', JSON.stringify(e.name));
  list.value = list.value.filter(name=>name!==e.name);
  console.log("删除后"+JSON.stringify(list.value))
  len=len-1;
}

</script>
<style lang="scss" scoped>
.information {
  margin: 5px;
  padding: 20px 60px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1), 0 6px 20px rgba(0, 0, 0, 0.1);
  border-radius: 30px; /* 你可以调整这个值来改变圆角的大小 */

  .title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    //border-bottom: 15px solid #4D7181;

    .icon {
      font-size: 35px;
      padding: 15px;
      color: white;
      margin-right: 20px;
      background-color: #C09E66;
      border-radius: 50px;
      margin-bottom: 10px;
    }
  }

  .basic {
    display: flex;
    padding-left: 30px;
    justify-content: space-between;

    .basicInfo {
      width: 70%;
      height: 100%;
      display: flex;
      flex-wrap: wrap; /* 允许子元素换行 */
      gap: 0 30px; /* 设置水平间距为10px，垂直间距为0 */
    }

    .update {
      margin-right: 100px;
    }
  }

  .school {
    width: 100%;
    padding-left: 30px;
    //justify-content: space-between;
    display: flex;

    flex-wrap: wrap; /* 允许子元素换行 */
    gap: 0 30px; /* 设置水平间距为10px，垂直间距为0 */
  }

  .update {
    margin-right: 100px;
    width: 170px;
    height: 170px;
    border-radius: 50%;
    //padding: 33px;
    //border: 1px solid #ccc;
  }

  :deep(.ant-upload-wrapper .ant-upload-disabled) {
    height: 170px;
    width: 170px;
    border: 2px solid #ccc;
    border-radius: 50%;
  }

  :deep(.ant-upload .ant-upload-disabled) {
    height: 170px;
    width: 170px;
    border: 2px solid #ccc;
    border-radius: 50%;
  }

  :deep(.ant-upload-wrapper.ant-upload-picture-card-wrapper .ant-upload.ant-upload-select) {
    height: 170px;
    width: 170px;
    border: 2px solid #ccc;
    border-radius: 50%;
  }

  :deep(.ant-upload .ant-upload-disabled) {
    height: 170px;
    width: 170px;
    border: 2px solid #ccc;
    border-radius: 50%;
  }
}

//.ant-upload-select-picture-card i {
//  font-size: 32px;
//  color: #999;
//}
//
//.ant-upload-select-picture-card .ant-upload-text {
//  margin-top: 8px;
//  color: #666;
//}
</style>
